package net.sourceforge.perforce.ui;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import net.sourceforge.perforce.core.internal.P4TeamProvider;
import net.sourceforge.perforce.core.resources.IChangelist;
import net.sourceforge.perforce.core.resources.LocalResource;
import net.sourceforge.perforce.ui.internal.AddToSourceControlRunnable;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.team.core.RepositoryProvider;


public class NewFilesPreSubmitOperation implements IPreSubmitOperation {
  private IProject[] projects;
  private IResource[] resources;

  public boolean perform(IChangelist changelist, IProgressMonitor monitor) {
    Map<RepositoryProvider, List<IResource>> map =
        P4TeamProvider.getProviderMapping(resources, monitor);

    AddToSourceControlRunnable runnable = new AddToSourceControlRunnable(map);
    try {
      runnable.run(monitor);
    } catch (InterruptedException e) {
      PerforceUIPlugin.handle(e);
      return false;
    } catch (InvocationTargetException e) {
      PerforceUIPlugin.handle(e);
      return false;
    }
    return true;
  }

  public boolean isEnabled(IChangelist changeList) throws CoreException {
    IPreferenceStore store = PerforceUIPlugin.getPlugin().getPreferenceStore();
    if (!store.getBoolean(IPerforceUIConstants.PREF_CHECK_FOR_NEWFILES_BEFORE_SUBMIT))
      return false;

    projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    return LocalResource.oneOrMoreResourcesNeedsAdding(projects);
  }

  public boolean collectUserInput(IChangelist changeList, Shell shell) {
    NewFilesDialog dlg = new NewFilesDialog(shell);
    if (dlg.open() == Dialog.OK) {
      resources = dlg.getSelectedResources();
      return true;
    }
    return false;
  }
}
